package kassiopeia.gui.utils

import java.util.ArrayList;
import java.util.List;
import kassiopeia.commons.log.Log;
import static com.google.common.base.Preconditions.*;

public class LogsBuffer {

    private int index
    private int size
    private int actualSize
    private Log[] buffer
    private long idCounter = 1

    LogsBuffer(int size) {
        checkArgument(size > 0)
        this.size = size
        this.buffer = new Log[size]
    }

    synchronized void offer(Log element) {
        checkNotNull(element)

        long id = idCounter++
        element.setLogId(id)

        buffer[index] = element

        if(index+1 >= size) {
            index = 0
        } else {
            index++
        }

        if(actualSize < size) {
            actualSize += 1
        }
    }

    synchronized List<Log> pollAll() {
        ArrayList<Log> results = new ArrayList<Log>()

        for(int i=index; i < size; i++) {
            if(buffer[i] != null) {
                results.add(buffer[i])
            }
        }

        for(int i=0; i < index; i++) {
            results.add(buffer[i])
        }

        return results
    }

    synchronized List<Log> pollFrom(long logId) {
        checkArgument(logId >= 0)

        ArrayList<Log> results = new ArrayList<Log>()

        for(int i=index; i < size; i++) {
            if((buffer[i] != null) && buffer[i].getLogId() >= logId) {
                results.add(buffer[i])
            }
        }

        for(int i=0; i < index; i++) {
            if(buffer[i].getLogId() >= logId) {
                results.add(buffer[i])
            }
        }

        return results
    }


    synchronized int size() {
        return size
    }

    synchronized int actualSize() {
        return actualSize
    }
}
